/**
 * 初始化
 */
$(document).ready(function() {
    App.init();
});
var App = {
    show_gift: false,
    //是否显示抽奖
    gift_total: 5,
    //设置抽的结果总
    gift_total_index:1,
    // gift_steams:['张山','李四','王二','麻子','王五','李三','张四','张杰','李飞','王朝'],
    gift_steams:[],
    gift_steams_tmp:[],
    //选用户的时钟
    gift_timer:null,
    //用户数组
    show_party: false,
    //幕布是否打开
    currentParty: null, 
    //当前活动的Paryty对象
    weixin:[],
    //微信数组
    lastWeixinId: 0,
    //最后一条微信
    skitterInterval: 2000,
    //幻灯片时间
    interval_weixin: 3000,
    //获取微信的时间间隔
    interval_weixin_timer: null,
    //获取微信的时钟
    interval_refresh_party: 3000,
    //刷新活动的时间间隔
    interval_refresh: null, 
    //刷新活动的时钟
    weixin_repeat_timer:null,
    weixin_repeat_interval:5000,

    luckySoundTimer:null,
    luckySoundLength:197000
    //微信重复时间
    //music_url:'http://www.xiami.com/widget/1111259_3589592,55700,163975,385186,_200_450_FF8719_494949_1/multiPlayer.swf'
    //音乐播放地址
};
/**
 * 初始化
 * @return {[type]}
 */
App.init = function() {
    var _self = this;

    _self.load(function() {
        _self.initEvent();
        _self.refreshParty();
        _self.refreshWeixin();
        _self.interval_refresh = setInterval(_self.refreshParty, _self.interval_refresh_party);
        _self.interval_weixin_timer = setInterval(_self.refreshWeixin, _self.interval_weixin);
        //App.show();
    });

    _self.resizeWindow();
    $(window).resize(_self.resizeWindow);
}

//当窗口大小改变的时候执行计算
App.resizeWindow = function() {
    var header_h = $('.header').height(),
        body_h = $(document).height(),
        content_h = body_h - header_h,
        sms_w = App.getSmsWidth();
    $('.sms').height(content_h).width();
    $('#secondary-box').height(content_h - 500);
}
App.getSmsWidth = function()
{
    var wrapper_w = $('.wrapper').width(),
        slide_w = $('.slide-box').width();
    return wrapper_w - slide_w -20;

}
//刷微信
App.refreshWeixin = function() {
    if (App.currentParty != null) {
        $.ajax({
            type: 'GET',
            url: APP + '/Weixin/next.html?lastId=' + App.lastWeixinId + '&partyId=' + App.currentParty.id,
            success: function(data) {
                if (data != null && typeof(data) == 'object') {
                    if (data['type'] == 'text') {
                        App.weixin.push(data);
                        App.lastWeixinId = data['id'];
                        //文本消息
                        App.showWeixin(data);
                        $('#secondary-box').append('<div class="user-item">'+data['fromUserName']+'</div>');
                    }
                }else{
                    if( App.weixin_repeat_timer == null) {
                        App.weixin_repeat_timer = setInterval(App.showRepeatWeixin,App.weixin_repeat_interval);
                    }
                }
            }
        });
    }
}
App.showRepeatWeixin = function(){
    var $box = $('#msg-box');
    var $last = $box.children('.sms-item').last();
    var html = $last[0];
    $last.fadeOut(600,function(){
        $box.prepend(html);
        var $first = $box.children('.sms-item').first();
        $first.slideDown(1000);
    });
    
}
//显示微信对象
App.showWeixin = function(data){
    var user = data['fromUserName'] != null ? data['fromUserName'] : '亲友';
    var msg = '<div class="sms-item hide">' + '<h4 class="text-gradient">@' + user + '发来祝福：</h4>' + '<div class="sms-content"><div class="tip-center">' + data['content'] + '</div></div></div>';
    $('#msg-box').prepend(msg).children('div.sms-item:first').slideDown(1000);//.effect('bounce');
}
//获取最后时间最近一个活动
App.latest = function(callback) {
    $.ajax({
        type: "GET",
        url: APP + "/Party/latest.html",
        success: callback
    });
}
App.viewById = function(callback) {
    $.ajax({
        type: "GET",
        url: APP + "/Kids/viewById.html",
        success: callback
    });
}
//显示对应ID的弹出层
App.showPopup = function(id) {
    switch (id) {
    case 'help':
        var d = $('#help');
        if (d.css('top') == '-400px') {
            d.stop().animate({'top':'250px'});
        } else {
            d.stop().animate({'top':'-400px'});
        }
        break;
    case 'gift':
        if (!App.show_gift) {
            App.initGift();
        } else {
            App.hideGift();
        }
        break;
    default:
        break;
    }
}

//初始化事件
App.initEvent = function() {
    var music = $('#music-flash');
    //music.children('embed').attr('src',App.music_url);
    music.mouseover(function(){ $(this).stop().animate({ 'left':'2%' },300); });
    music.mouseout(function(){ $(this).stop().animate({ 'left':'-210px'},300); });

    $('#gift-btn').click(App.choseGiftEvent);
    $('.header-menu-content ul li').click(function(){
        $(this).parent('ul').children('li').removeClass('active');
        $(this).addClass('active');
    });
}
/**
 * 选择中奖用户事件
 * @return {[type]}
 */
App.choseGiftEvent = function()
{
    var obj = $(this),
        title = obj.attr('title');
    if(App.gift_total >0){
        if(title=="开始抽奖" || title == "继续抽奖"){
            //$('#gift-user').prepend('<div class="gift-user-item"><div class="gift-label"></div><div class="gift-user-name"></div></div>');
            // App.gift_timer = setInterval(function(){
            //     var luck = App.choseOne();
            //     $('.gift-user-name').first().html(luck);
            // },50);
            // obj.attr('title','停止抽奖').attr('class','gift-end');
            //var luck = App.gift_timer.chose();
            if(App.gift_steams_tmp.length === 0){
                alert('所有亲友已经中奖');
                return false;
            }
            var luck = App.choseOne();
            App.removeFromLuckArr(luck);
            App.showLuckOne(luck,App.gift_total_index);
            App.gift_total_index ++;
            App.gift_total--;
            $('#total-left').html(App.gift_total);
            //$('.gift-user-name').first().html(luck);s

            

            if(App.gift_total >0){
                obj.attr('title','继续抽奖').attr('class','gift-continue');
            }else{
                obj.attr('title','抽奖结束').attr('class','gift-finish');
            }
        }else if(title == "停止抽奖"){

            // clearInterval(App.gift_timer);
            // var luck = $('.gift-user-name').first().html();
            // App.removeFromLuckArr(luck);

            if(App.gift_total >0){
                obj.attr('title','继续抽奖').attr('class','gift-continue');
            }else{
                obj.attr('title','抽奖结束').attr('class','gift-finish');
            }
        }
    }else{
        obj.attr('title','抽奖结束').attr('class','gift-finish');
    }
}

App.showLuckOne = function(name,index)
{
    var chNum = index;//Public.getChNum(index);
    var box = $('#luck-one-box');
    var h = $('#luck-one-box h4');
    var p = $('#luck-one-box p');
    var h_html = "第 "+chNum+" 位幸运亲友";
    h.html(h_html);
    p.html(name);
    box.animate({"height":"350px"},600,function(){
        p.fadeIn().effect({
            effect:'bounce',
            duration:600,
            easing:'easeInOutElastic'
        });
        App.playLuckyChoseSound();
        setTimeout(function(){
            // h.animate({"font-size":'18px'},300);
            // p.animate({"font-size":'40px'},300);
            var sms_w = App.getSmsWidth() - 40;
            box.animate({
                "left": "710px",
                "margin-top": "60px",
                "width":sms_w+"px"
            },1000,function(){
                $('#gift-user').append('<div class="gift-user-item"><div class="gift-label"></div><h4>'+h_html+'</h4><div class="gift-user-name">'+name+'</div></div>');    
                box.fadeOut(600,function(){
                    box.css({
                        "width":"670px",
                        "margin-top":0,
                        "left":'2%',
                        'height':0,
                        'display':'block'
                    });
                    p.css('display','none');
                });
                App.stopLuckyChoseSound();
            });
        },3000);
    });
}
/**
 * 从数组中随机产生一个元素
 * @return {[type]}
 */
App.choseOne = function()
{
    var random = Public.random(App.gift_steams_tmp);
    return random;
}



/**
 * 从亲友数组中删除一个并将抽奖数字减一
 * @return {[type]}
 */
App.removeFromLuckArr = function(name)
{
    for(var i=0;i<App.gift_steams_tmp.length;i++){
        if(App.gift_steams_tmp[i] === name){
            App.gift_steams_tmp.splice(i,1);
            break;
        }
    }
    //App.gift_total-- ;
}

//现实抽奖
App.initGift = function() {
    if(App.currentParty === null){
        alert('当前没有婚庆活动');
        return false;
    }
    if(!App.show_gift){
        if(App.gift_steams.length == 0){
            App.getLuckyArr(function(data){
                if(data!=null && data.length>0){
                    App.gift_steams = data;
                    App.gift_steams_tmp = data;
                    $('#total-left').html(App.gift_total);
                    App.showGift();
                }else{
                    alert('暂无可抽奖的用户');
                }
            });
        }else{
            App.showGift();
        }
    }
    
    //App.showGift(App.gift_steams);
}
/**
 * 获取抽奖用户数组
 */
App.getLuckyArr = function(callback)
{
    $.ajax({
        type:"GET",
        url:APP+"/Weixin/users.html?begin="+App.currentParty.begin,
        error:function(e){
            alert('ERROR:'+e);
        },
        success:callback
    });
}
/**
 * 根据指定的用户数组抽奖
 * @param  {[type]} data
 * @return {[type]}
 */
App.showGift = function()
{
    App.stopXiami();
    App.playLuckySound();
    
    $('#gift-panel').animate({ top: '272px' }, 600, 
        function() 
        {
            App.show_gift = true;
            $('#image-box').fadeOut();
            $('#msg-box').fadeOut();

            $('.title').removeClass('good').addClass('lucky');
            $('#gift-panel').fadeIn();
            $('#gift-user-box').fadeIn();
            $('#gift-users-list').fadeIn();

            var url = PUBLIC+"/upload/"+App.currentParty.images[0].name;
            url = url.replace(/\\/g,'/');
            $('#gift-user-list-mask').css({
                'display':'block',
                'background':'url("'+url+'") no-repeat center top',
                'background-size':'100%'
            });

            if(App.gift_timer == null){

                // var arr = App.gift_steams;
                // while(arr.length<5){
                //     arr[arr.length]=App.choseOne();
                // }

                App.gift_timer = setInterval(function(){
                    var random = App.choseOne();
                    $('#user-coffee').html(random);
                },200);

                // App.gift_timer = $('#user-coffee').empty().css('height','350px').lucky({
                //     Arr:arr,
                //     Interval:100
                // });
            }
            // $('#user-coffee').empty().css('height','2px').coffee({
            //     steams: App.gift_steams,
            //     // steamsFontFamily: ['Verdana', 'Geneva', 'Arial', 'Courier New', 'Georgia'],
            //     steamsFontFamily: ['Microsoft Yahei','sans-serif'],
            //     steamFlyTime: 7000,
            //     /*Steam飞行的时间,单位 ms 。（决定steam飞行速度的快慢）*/
            //     makeSteamInterval: 200,
            //     /*制造Steam时间间隔,单位 ms.*/
            //     steamMaxSize: 50,
            //     steamTopMax: 400,
            //     /*蒸汽飞行最大高度.*/
            //     coffeeHandleWidth: 400 /*咖啡杯的手柄宽度.*/
            // });
        }
    );
}

//隐藏抽奖界面
App.hideGift = function() {
    $('#gift-panel').fadeOut();
    $('#gift-users-list').fadeOut();
    $('#gift-user-list-mask').css('display','none');

    $('.title').removeClass('lucky').addClass('good');
    $('#image-box').fadeIn();
    $('#msg-box').fadeIn();

    App.show_gift = false;
    App.playXiami();
    App.stopLuckySound();
}
//延迟加载
App.load = function(callback) {
    var css = [ PUBLIC + "/css/skitter.styles.min.css"],
        js = [
            PUBLIC + "/js/Public.js", 
            PUBLIC + "/js/jquery.easing.1.3.js", 
            PUBLIC + "/js/jquery.skitter.min.js", 
            PUBLIC + "/js/jquery.coffee.js",
            PUBLIC + "/js/jquery.lucky.js"
        ];
    LazyLoad.css(css, function() {});
    LazyLoad.js(js, callback ? callback : function() {});
}
//刷新活动
App.refreshParty = function() {
    App.latest(function(data) {
        if (data) {
            var begin = new Date(data.begin.replace(/\-|\-/g, '/')),
                end = new Date(data.end.replace(/\-|\-/g, '/')),
                now = new Date(),
                toend = end.getTime() - now.getTime();
            if (data.begin < Public.nowStr() && data.end > Public.nowStr()) {
                if (!App.show_party) {
                    var imgs = data.images,
                        imgarr = [];
                    App.currentParty = data;
                    $.each(imgs, function(i, k) {
                        var url = k.name.replace(/\\/g,'/');
                        imgarr.push('<li><a href="javascript:;"><img src="' + PUBLIC + '/upload/' + url + '" /></a></li>');
                    });
                    $('.box_skitter ul').html(imgarr.join(''));

                    $('#rightMan').html(data.man);
                    $('#rightWoman').html(data.woman);

                    setTimeout(function() {
                        App.show();
                        App.skitter();
                        App.hideHelp();
                    }, 1000);

                    clearInterval(App.interval_refresh);
                    //结束时继续开始刷新
                    setTimeout(function() {
                        App.interval_refresh = setInterval(App.refreshParty, App.interval_refresh_party);
                    }, toend);
                }
            } else if (data.begin > Public.nowStr()) {
                var date3 = begin.getTime() - now.getTime(); //时间差的毫秒数
                var days = Math.floor(date3 / (24 * 3600 * 1000)); //计算出相差天数
                //计算出小时数
                var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
                var hours = Math.floor(leave1 / (3600 * 1000));
                //计算相差分钟数
                var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
                var minutes = Math.floor(leave2 / (60 * 1000));
                //计算相差秒数
                var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
                var seconds = Math.round(leave3 / 1000);

                $('#day b').html(days);
                $('#hour b').html(hours);
                $('#min b').html(minutes);
                $('#sec b').html(seconds);

                $('#info-man').html(data.man);
                $('#info-woman').html(data.woman);

                App.hide();
            }else{
                App.blankPartyInfo();
                App.hide();
            }
        } else {
            App.blankPartyInfo();
            App.hide();
        }
    });
}
App.blankPartyInfo = function()
{
    $('#day b').html("--");
    $('#hour b').html("--");
    $('#min b').html("--");
    $('#sec b').html("--");
    $('#info-man').html("--");
    $('#info-woman').html("--");
}
App.showHelp = function() {
    if ($('#help').css('top') == '-400px') $('.help').click();
}
App.hideHelp = function() {
    if ($('#help').css('top') == '250px') $('.help').click();
}
//拉起幕布
App.show = function() {
    $('#mubu').animate({
        'top': '-4000px'
    }, 1000, function() {
        App.show_party = true;
    });
    $('#partyInfo').stop().animate({'top':'-400px'});
    this.hideHelp();
}
//放下幕布
App.hide = function() {
    $('#mubu').animate({
        'top': '0'
    });
    $('#partyInfo').stop().animate({'top':'90px'});
    this.showHelp();
    this.show_party = false;
}
//幻灯片
App.skitter = function() {
    $('.box_skitter').skitter({
        controls: false,
        navigation: false,
        label: false,
        numbers: false,
        stop_over:false,
        theme: 'square',
        interval: App.skitterInterval,
        with_animations: ['paralell', 'glassCube', 'swapBars', 'block', 'cubeHide', 'cubeSize', 'horizontal', 'fade', 'fadeFour', 'blind', 'cubeSpread', 'cubeJelly', 'glassBlock', 'circles', 'circlesInside', 'cubeShow', 'hideBars', 'swapBlocks', 'cut']
    });
}
App.stopXiami = function()
{
    App['xiami'] = $('#music-flash').html();
    $('#music-flash embed').detach();
}
App.playXiami = function()
{
    $('#music-flash').html(App['xiami']);
}
//播放抽奖音乐
App.playLuckySound = function()
{
    $('#lucky-sound').append('<embed src="'+PUBLIC+'/asset/lucky-bg.mp3" autostart=true loop=20 hidden=true ></embed>');
    App.luckySoundTimer = setInterval(function(){
        $('#lucky-sound').append('<embed src="'+PUBLIC+'/asset/lucky-bg.mp3" autostart=true loop=20 hidden=true ></embed>');
    },App.luckySoundLength);

}
//清除抽奖音乐
App.stopLuckySound = function()
{
    $('#lucky-sound').empty();
    clearInterval(App.luckySoundTimer);
    App.luckySoundTimer = null;
}
//播放抽奖音乐
App.playLuckyChoseSound = function()
{
    $('#lucky-chose-sound').append('<embed src="'+PUBLIC+'/asset/waO.wav" autostart=ture loop=false hidden=true playcount=false></embed>');
}
//清除抽奖音乐
App.stopLuckyChoseSound = function()
{
    $('#lucky-chose-sound').empty();
}

App.showGiftTotalEdit = function(){
    $('#total-left').hide();
    $('#total-edit').show().children('input').val(App.gift_total);
}
App.saveGiftTotal = function(){
    var total = $('#total-edit').children('input').val();
    var reg = /^\d+$/;
    if(reg.test(total)){
        total = parseInt(total);
        if(total > App.gift_steams_tmp.length){
            alert("抽奖数字大于了亲友总数");
        }else{
            App.gift_total = total;
            $('#total-left').html(total).show();
            $('#total-edit').hide();
            if(App.gift_total_index > 1){
                $('#gift-btn').attr('title','继续抽奖').attr('class','gift-continue');
            }            
        }
    }else{
        alert('请输入正确的抽奖数字');
        return false;
    }
}

